import { _decorator, AudioClip, Component, director, Node } from "cc";
import { BombUI } from "./UI/BombUI";
import { ScoreUI } from "./UI/ScoreUI";
import { Player } from "./Player";
import { GameOverUI } from "./UI/GameOverUI";
import { AudioMgr } from "./AudioMgr";
const { ccclass, property } = _decorator;

@ccclass("GameManager")
export class GameManager extends Component {
  @property
  bombNum: number = 0;

  @property(Player)
  public player: Player = null;

  @property(BombUI)
  public bombUI: BombUI = null;

  @property
  public score: number = 0;

  @property(ScoreUI)
  public scoreUI: ScoreUI = null;

  @property(GameOverUI)
  public gameOverUI: GameOverUI = null;

  @property(Node)
  public pauseButton: Node = null;

  @property(Node)
  public resumeButton: Node = null;

  @property(AudioClip)
  public audioBg: AudioClip = null;

  @property(AudioClip)
  public audioUseBomb: AudioClip = null;

  @property(AudioClip)
  public audioButtonClick: AudioClip = null;

  @property(AudioClip)
  public audioGameOver: AudioClip = null;

  public static instance: GameManager = null;

  protected onLoad(): void {
    GameManager.instance = this;
  }

  protected start(): void {
    AudioMgr.inst.playOneShot(this.audioBg, 0.2);
  }

  public static getInstance(): GameManager {
    return GameManager.instance;
  }
  public addBomb(): void {
    this.bombNum++;
    // this.node.emit("onBombChange", this.bombNum);
    this.bombUI.onBombChange(this.bombNum);
  }

  public useBomb() {
    this.bombNum--;
    this.bombUI.onBombChange(this.bombNum);
    AudioMgr.inst.playOneShot(this.audioUseBomb, 0.2);
  }

  // 更新分数
  public addScore(score: number): void {
    this.score += score;
    this.scoreUI.updateScore(this.score);
  }

  // 暂停游戏
  public gamePause() {
    director.pause();
    this.player.disabledController();
    this.pauseButton.active = false;
    this.resumeButton.active = true;
    AudioMgr.inst.playOneShot(this.audioButtonClick, 0.2);
  }

  // 恢复游戏
  public gameResume() {
    director.resume();
    this.player.enableController();
    this.pauseButton.active = true;
    this.resumeButton.active = false;
    AudioMgr.inst.playOneShot(this.audioButtonClick, 0.2);
  }

  // 游戏结束
  public gameOver() {
    const highestScore = localStorage.getItem("highestScore");
    AudioMgr.inst.playOneShot(this.audioGameOver, 0.2);
    let score = 0;
    if (highestScore) {
      score = parseInt(highestScore);
    }

    if (this.score > score) {
      localStorage.setItem("highestScore", this.score.toString());
    }

    this.gameOverUI.showGameOverUI(score, this.score);
    this.gamePause();
  }

  public onRestartButtonClicked() {
    // this.gameOverUI.hideGameOverUI();
    // const currentSence = director.getScene();
    director.loadScene("Game");
    this.gameResume();
    AudioMgr.inst.playOneShot(this.audioButtonClick, 0.2);
  }

  public onQuitButtonClicked() {}

  // 是否有炸弹
  public isHaveBomb(): boolean {
    return this.bombNum > 0;
  }
}
